﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Domain.Entities;
using Core.Extensions;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Roles.Caching;
using Core.Identity.Roles.Dtos;
using Core.Models;
using Gridify;
using Gridify.EntityFramework;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Roles.Features.Queries.WithPagination;

public class RolesWithPaginationQuery : GridifyQuery, ICacheableRequest<PaginatedData<RoleDto>>
{
    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => RolesCacheKey.GetPaginationCacheKey($"{Page}_{PageSize}_{OrderBy}_{Filter}");
    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string>? Tags => RolesCacheKey.Tags;
}

public class RolesWithPaginationQueryHandler :
         IRequestHandler<RolesWithPaginationQuery, PaginatedData<RoleDto>>
{
    private readonly IIdentityDbContext _context;

    public RolesWithPaginationQueryHandler(
        IIdentityDbContext context)
    {
        _context = context;
    }

    public async Task<PaginatedData<RoleDto>> Handle(RolesWithPaginationQuery request, CancellationToken cancellationToken)
    {
        return (await _context.Roles
            .AsNoTracking()
            .GridifyAsync(request, cancellationToken))
            .ToPaginatedList<Role, RoleDto>(request.Page, request.PageSize);
    }
}
